<?php

namespace x_mier\utils;

class WxLogin
{
    //APP
    public $appId = '';
    public $appSecret = '';
    // 小程序
    public $appId2 = '';
    public $appSecret2 = '';
    //公众号
    public function __construct($appId = '', $appSecret = '', $type = false)
    {
        if ($appId && $appSecret) {
            if ($type) {
                $this->appId2 = $appId;
                $this->appSecret2 = $appSecret;
            } else {
                $this->appId = $appId;
                $this->appSecret = $appSecret;
            }
        } else {
            $config = config('plugin.x_mier.doc.app');
            if ($config && !empty($config['wx_login'])) {
                $config = $config['wx_login'];
                $this->appId = $config['app_id'];
                $this->appSecret = $config['app_secret'];
                $this->appId2 = $config['app_id2'];
                $this->appSecret2 = $config['app_secret2'];
            }
        }
    }
    public function userinfo($code)
    {
        $tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appId}&secret={$this->appSecret}&code={$code}&grant_type=authorization_code";
        $response = file_get_contents($tokenUrl);
        $data = json_decode($response, true);
        if (isset($data['errcode'])) {
            throw new \Exception("登录失败,请稍后重试!");
        }
        $accessToken = $data['access_token'];
        $openId = $data['openid'];
        // 第二步：使用access_token和openid获取用户信息  
        $userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token={$accessToken}&openid={$openId}&lang=zh_CN";
        $userInfoResponse = file_get_contents($userInfoUrl);
        $userInfo = json_decode($userInfoResponse, true);
        if (isset($userInfo['errcode'])) {
            throw new \Exception("获取用户信息失败: " . $userInfo['errmsg']);
        }
        return $userInfo;
    }
    //小程序获取openid
    public function getOpenid($code)
    {
        $tokenUrl = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appId2}&secret={$this->appSecret2}&js_code={$code}&grant_type=authorization_code";
        $response = file_get_contents($tokenUrl);
        $data = json_decode($response, true);
        return $data;
    }
}
